package com.uduemc.biso.node.module.common.controller;

import com.uduemc.biso.core.utils.RestResult;
import com.uduemc.biso.node.core.common.entities.PageSystem;
import com.uduemc.biso.node.core.dto.FeignFindInfosByHostSiteAndSystemTypeIds;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.module.common.service.CPageService;
import com.uduemc.biso.node.module.service.SPageService;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.List;

@RestController
@RequestMapping("/common/page")
public class CPageController {

    @Resource
    private CPageService cPageServiceImpl;

    @Resource
    private SPageService sPageServiceImpl;

    /**
     * 通过 hostId、siteId获取系统页面，并且系统类型在 systemTypeIds 中的数据
     *
     * @param feignFindInfosByHostSiteAndSystemTypeIds
     * @return
     */
    @PostMapping("/find-system-page-by-host-site-id-and-system-types")
    public RestResult findSystemPageByHostSiteIdAndSystemTypes(
            @Valid @RequestBody FeignFindInfosByHostSiteAndSystemTypeIds feignFindInfosByHostSiteAndSystemTypeIds) {
        long hostId = feignFindInfosByHostSiteAndSystemTypeIds.getHostId();
        long siteId = feignFindInfosByHostSiteAndSystemTypeIds.getSiteId();
        List<Long> systemTypeIds = feignFindInfosByHostSiteAndSystemTypeIds.getSystemTypeIds();
        if (hostId < 1 || siteId < 1 || CollectionUtils.isEmpty(systemTypeIds)) {
            return RestResult.noData();
        }
        List<PageSystem> data = cPageServiceImpl.findSystemPageByHostSiteIdAndSystemTypes(hostId, siteId,
                systemTypeIds);

        return RestResult.ok(data, PageSystem.class.toString(), true);
    }

    /**
     * 通过传递过来的参数，删除页面数据，同时删除跟页面相关的数据
     *
     * @param hostId
     * @param siteId
     * @param pageId
     * @return
     */
    @GetMapping("/delete/{hostId:\\d+}/{siteId:\\d+}/{pageId:\\d+}")
    public RestResult delete(@PathVariable("hostId") long hostId, @PathVariable("siteId") long siteId,
                             @PathVariable("pageId") long pageId) {
        SPage sPage = sPageServiceImpl.findSPageByIdHostSiteId(pageId, hostId, siteId);
        if (sPage == null) {
            // 直接删除跟 pageId 相关的所有 page 数据
            cPageServiceImpl.deletePage(hostId, siteId, pageId);
            return RestResult.ok(1);
        }
        cPageServiceImpl.deletePage(sPage);
        return RestResult.ok(sPage);
    }
}
